package com.teacher.game.state;

import android.graphics.Color;
import android.view.MotionEvent;
import com.teacher.ellio.Assets;
import com.teacher.ellio.GameMainActivity;
import com.teacher.game.framework.util.Painter;
import com.teacher.game.framework.util.ScoreManager;
import com.teacher.game.framework.util.UIButton;

/**
 * 得分统计界面 - 显示游戏历史统计和记录
 */
public class ScoreState extends State {
    
    private ScoreManager scoreManager;
    private UIButton backButton;
    private UIButton clearDataButton;
    
    // 显示内容
    private String highScoreText;
    private String totalGamesText;
    private String averageScoreText;
    private String playerLevelText;
    private String scoringRulesText;
    
    // 动画效果
    private float titlePulse = 0;
    private boolean showClearConfirm = false;
    
    @Override
    public void init() {
        // 初始化得分管理器
        scoreManager = new ScoreManager(GameMainActivity.sGame.getContext());
        
        // 创建按钮 - 调整位置避免重叠
        backButton = new UIButton(50, 390, 182, 449, Assets.start, Assets.startDown);
        clearDataButton = new UIButton(618, 390, 750, 449, Assets.score, Assets.scoreDown);
        
        // 准备显示数据
        prepareDisplayData();
    }
    
    /**
     * 准备要显示的统计数据
     */
    private void prepareDisplayData() {
        highScoreText = "历史最高分: " + scoreManager.getHighScore();
        totalGamesText = "总游戏次数: " + scoreManager.getTotalGames();
        averageScoreText = "平均得分: " + scoreManager.getAverageScore();
        playerLevelText = "玩家等级: Lv." + scoreManager.getPlayerLevel();
        scoringRulesText = scoreManager.getScoringRules();
    }
    
    @Override
    public void update(float delta) {
        // 标题脉动效果
        titlePulse += delta * 2;
        
        // 更新跑步动画
        Assets.runAnim.update(delta);
    }
    
    @Override
    public void render(Painter g) {
        // 渲染背景
        renderBackground(g);
        
        // 渲染标题
        renderTitle(g);
        
        // 渲染统计信息
        renderStatistics(g);
        
        // 渲染得分规则
        renderScoringRules(g);
        
        // 渲染按钮
        renderButtons(g);
        
        // 渲染确认对话框
        if (showClearConfirm) {
            renderClearConfirmDialog(g);
        }
    }
    
    /**
     * 渲染背景
     */
    private void renderBackground(Painter g) {
        // 使用欢迎背景
        g.drawImage(Assets.welcome, 0, 0);
        
        // 半透明遮罩
        g.setColor(Color.argb(180, 0, 50, 100));
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, GameMainActivity.GAME_HEIGHT);
    }
    
    /**
     * 渲染标题
     */
    private void renderTitle(Painter g) {
        // 标题带脉动效果
        float titleScale = 1.0f + (float) Math.sin(titlePulse) * 0.05f;
        
        g.setColor(Color.WHITE);
        g.drawString("游戏统计", 350, 50);
        
        // 装饰性跑步小人
        Assets.runAnim.render(g, 280, 55);
        Assets.runAnim.render(g, 470, 55);
    }
    
    /**
     * 渲染统计信息
     */
    private void renderStatistics(Painter g) {
        int startY = 100;
        int lineHeight = 28; // 减少行间距
        
        // 主要统计数据
        g.setColor(Color.YELLOW);
        g.drawString(highScoreText, 200, startY);
        
        g.setColor(Color.WHITE);
        g.drawString(totalGamesText, 200, startY + lineHeight);
        g.drawString(averageScoreText, 200, startY + lineHeight * 2);
        
        g.setColor(Color.CYAN);
        g.drawString(playerLevelText, 200, startY + lineHeight * 3);
        
        // 额外统计信息
        if (scoreManager.getTotalGames() > 0) {
            g.setColor(Color.rgb(192, 192, 192));
            g.drawString("总障碍物越过: " + scoreManager.getTotalBlocksPassed(), 200, startY + lineHeight * 4);
            
            float totalHours = scoreManager.getTotalPlayTime() / 3600f;
            g.drawString(String.format("总游戏时长: %.1f小时", totalHours), 200, startY + lineHeight * 5);
        }
        
        // 成就系统预览
        renderAchievements(g, startY + lineHeight * 6 + 10);
    }
    
    /**
     * 渲染成就信息
     */
    private void renderAchievements(Painter g, int startY) {
        g.setColor(Color.rgb(255, 215, 0)); // 金色
        g.drawString("🏆 成就系统:", 200, startY);
        
        g.setColor(Color.WHITE);
        
        // 根据统计数据显示成就，调整间距
        if (scoreManager.getHighScore() >= 1000) {
            g.drawString("✅ 得分达人 - 单局得分超过1000", 220, startY + 20);
        } else {
            g.setColor(Color.GRAY);
            g.drawString("❌ 得分达人 - 单局得分超过1000", 220, startY + 20);
        }
        
        g.setColor(scoreManager.getTotalGames() >= 10 ? Color.WHITE : Color.GRAY);
        String gameIcon = scoreManager.getTotalGames() >= 10 ? "✅" : "❌";
        g.drawString(gameIcon + " 游戏老手 - 累计游戏10次", 220, startY + 40);
    }
    
    /**
     * 渲染得分规则
     */
    private void renderScoringRules(Painter g) {
        g.setColor(Color.rgb(192, 192, 192));
        g.drawString("计分规则:", 50, 280);
        
        g.setColor(Color.WHITE);
        String[] rules = {
            "• 生存时间: 10分/秒",
            "• 越过障碍: 50分/个", 
            "• 跳跃动作: 10分/次",
            "• 下蹲动作: 10分/次",
            "• 连续躲避: 25分奖励"
        };
        
        for (int i = 0; i < rules.length; i++) {
            g.drawString(rules[i], 60, 300 + i * 18); // 缩小间距
        }
    }
    
    /**
     * 渲染按钮
     */
    private void renderButtons(Painter g) {
        backButton.render(g);
        clearDataButton.render(g);
        
        // 按钮标签
        g.setColor(Color.WHITE);
        g.drawString("返回菜单", 70, 465);
        g.drawString("清除数据", 638, 465);
    }
    
    /**
     * 渲染清除数据确认对话框
     */
    private void renderClearConfirmDialog(Painter g) {
        // 半透明背景
        g.setColor(Color.argb(200, 0, 0, 0));
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, GameMainActivity.GAME_HEIGHT);
        
        // 对话框背景
        g.setColor(Color.rgb(50, 50, 50));
        g.fillRect(200, 150, 400, 150);
        
        // 边框
        g.setColor(Color.WHITE);
        g.fillRect(200, 150, 400, 3); // 顶边
        g.fillRect(200, 297, 400, 3); // 底边
        g.fillRect(200, 150, 3, 150); // 左边
        g.fillRect(597, 150, 3, 150); // 右边
        
        // 确认文本
        g.setColor(Color.YELLOW);
        g.drawString("确认清除所有数据？", 320, 200);
        
        g.setColor(Color.WHITE);
        g.drawString("这将删除所有游戏记录", 320, 230);
        g.drawString("此操作无法撤销", 340, 250);
        
        g.setColor(Color.rgb(192, 192, 192));
        g.drawString("点击任意位置取消", 330, 280);
    }
    
    @Override
    public boolean onTouch(MotionEvent e, int scaleX, int scaleY) {
        if (e.getAction() == MotionEvent.ACTION_DOWN) {
            if (showClearConfirm) {
                // 在确认对话框状态下，任意点击都取消
                showClearConfirm = false;
                return true;
            }
            
            backButton.onTouchDown(scaleX, scaleY);
            clearDataButton.onTouchDown(scaleX, scaleY);
            
        } else if (e.getAction() == MotionEvent.ACTION_UP) {
            if (showClearConfirm) {
                return true; // 在确认状态下不处理按钮
            }
            
            if (backButton.isPressed(scaleX, scaleY)) {
                backButton.cancel();
                onBackToMenu();
                return true;
                
            } else if (clearDataButton.isPressed(scaleX, scaleY)) {
                clearDataButton.cancel();
                onClearDataRequest();
                return true;
                
            } else {
                backButton.cancel();
                clearDataButton.cancel();
            }
        }
        return true;
    }
    
    /**
     * 返回主菜单
     */
    private void onBackToMenu() {
        Assets.playSound(Assets.startId);
        setCurrState(new MenuState());
    }
    
    /**
     * 清除数据请求
     */
    private void onClearDataRequest() {
        if (scoreManager.getTotalGames() > 0) {
            // 如果有数据，显示确认对话框
            showClearConfirm = true;
            Assets.playSound(Assets.startId);
            
            // 3秒后自动执行清除（模拟长按确认）
            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (showClearConfirm) {
                        executeClearData();
                    }
                }
            }, 3000);
            
        } else {
            // 没有数据时提示
            Assets.playSound(Assets.startId);
        }
    }
    
    /**
     * 执行清除数据
     */
    private void executeClearData() {
        scoreManager.clearAllData();
        showClearConfirm = false;
        
        // 刷新显示数据
        prepareDisplayData();
        
        // 播放音效
        Assets.playSound(Assets.hitSoundId);
    }
    
    /**
     * 获取得分管理器
     */
    public ScoreManager getScoreManager() {
        return scoreManager;
    }
}